
// @ts-nocheck
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { renderWithQiankun, qiankunWindow } from 'vite-plugin-qiankun/dist/helper';

// 1. 类型声明
type QiankunProps = {
  container?: HTMLElement;
  [key: string]: any;
};

// 2. 渲染函数
const render = (props: QiankunProps = {}) => {
  const container = props.container;
  const dom = container
    ? container.querySelector('#root')
    : document.getElementById('root');

  if (!dom) {
    throw new Error('[Qiankun] #root element not found');
  }

  const root = ReactDOM.createRoot(dom);
  root.render(<App {...props} />);
};

// 3. 暴露生命周期
renderWithQiankun({
  mount(props: QiankunProps) {
    console.log('[react-sub] mount', props);
    render(props);
  },
  bootstrap() {
    console.log('[react-sub] bootstrap');
  },
  unmount(props: QiankunProps) {
    console.log('[react-sub] unmount');
    // React 18 无 destroyRoot，直接清 DOM
    const dom = props.container?.querySelector('#root') ?? document.getElementById('root');
    if (dom) dom.innerHTML = '';
  },
  // 加一个 update 方法满足qiankun类型要求
  update(props: QiankunProps) {
    console.log('[react-sub] update', props);
    render(props);
  }
});

// 4. 独立运行
if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
  render();
}
